package control;

import java.io.IOException;
import java.security.NoSuchAlgorithmException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import model.MD5;
import model.User;
public class Login extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public Login() {
		super();
	}
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
	}
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String name = request.getParameter("user");
		String pass = request.getParameter("pass");
		try {
			pass = MD5.encode(pass);
		} catch (NoSuchAlgorithmException e) {
			System.out.println("[Login] Không thể mã hóa MD5");
		}
			User user = new User(name, pass);
			String isExist = user.checkLogin();
			
			if (isExist == "") {
				// Dat Session
				User info = user.getUserByName(user.getUserName());
				HttpSession session = request.getSession();
				session.setAttribute("uid", info.getUid());
				session.setAttribute("user", name);
				session.setAttribute("lv", info.getUser_level());
				// Ket Thuc Session
				request.setAttribute("m", "login-ok");
				request.setAttribute("r","in");
				RequestDispatcher transfer = getServletContext()
						.getRequestDispatcher("/message.jsp");
				transfer.forward(request, response);
			} else {
				request.setAttribute("erlg", isExist);
				RequestDispatcher transfer = getServletContext()
						.getRequestDispatcher("/login.jsp");
				transfer.forward(request, response);
			}
		}
}
